<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="list">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <!-- 根据编辑状态 条件判断 -->
            <el-input v-if="row.isEdit" v-model="row.editRow.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义列结构 -->
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :inactive-value="0" :active-value="1" size="mini" />
            <span v-else> {{ row.state === 1 ? "已启用" : row.state === 0 ? "未启用" : "无" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <!-- 放置操作按钮 -->
          <template #default="{ row }">
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirmEdit(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnRowEdit(row)">编辑</el-button>
              <el-popconfirm title="确认要删除该数据么?" @onConfirm="del(row)">
                <el-button slot="reference" style="margin-left: 10px;" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>

        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <!-- 新增角色对话框 -->
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="cancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="roleForm.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <!-- 如果不需要校验 就不需要写 prop属性 -->
          <el-switch v-model="roleForm.state" :active-value="1" :inactive-value="0" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <!-- 按钮 -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="confirm">确定</el-button>
              <el-button size="mini" @click="cancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限 -->
    <el-dialog title="分配权限" :visible.sync="showPermissionDialog">
      <el-tree ref="permissionTree" node-key="id" :default-checked-keys="permIds" show-checkbox :data="permissionList" :props="defaultProps" default-expand-all />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnOK">确定</el-button>
          <el-button size="mini" @click="showPermissionDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getPermissionList } from '@/api/permission'
import { addRole, delRole, getRoleDetail, getRoleList, updateRole, assignPermissions } from '@/api/role'
import { translateListToTreeeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 第几页
        pagesize: 5, // 每页多少条
        total: 0
      },
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      showPermissionDialog: false, // 分配权限弹出层
      permissionList: [], // 权限列表
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      currentRoleId: null, // 角色id
      permIds: [] // 选中的权限id列表
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 点击确定分配权限
    async btnOK() {
      await assignPermissions({
        id: this.currentRoleId,
        permIds: this.$refs.permissionTree.getCheckedKeys()
      })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    // 分配权限
    async btnPermission(id) {
      // 点击时, 将权限列表置空
      this.permIds = []
      // 获取数据 渲染树形组件 translatexxx 转换
      this.permissionList = translateListToTreeeData(await getPermissionList(), 0)

      // 赋值角色id
      this.currentRoleId = id
      // 获取角色对应的权限列表
      const { permIds } = await getRoleDetail(id)
      console.log(permIds)
      this.permIds = permIds

      // 显示弹层 - 为了保证数据获取成功之后, 再进行渲染
      this.showPermissionDialog = true
    },

    // 获取角色列表
    async getRoleList() {
      const { rows, total } = await getRoleList(this.pageParams)
      this.list = rows // 赋值数据
      // 遍历角色数组 -> 给每一项添加编辑标识 true 编辑效果 / false  默认效果
      this.list.forEach(item => {
        // vue针对于动态添加的属性 不具备响应式的 (响应式: 数据变化, 视图会自动更新)
        // 问题: item.属性名 = 属性值 该属性不具备响应式 (vue2 object.defineProperty() 的缺陷 / vue3 proxy)
        // item.isEdit = false // 默认是非编辑状态
        // 解决: this.$set(目标对象, 属性名, 属性值)
        this.$set(item, 'isEdit', false)
        // 添加缓存数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
      this.pageParams.total = total
    },
    // 编辑角色
    btnRowEdit(row) {
      // 编辑状态 false -> true
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    // 确认编辑
    async confirmEdit(row) {
      console.log('行数据', row)
      // 1. 检查输入框的内容是否为空
      if (row.editRow.name && row.editRow.description) {
        // 2. 提交请求 - 更新角色
        await updateRole({ ...row.editRow, id: row.id })
        // 3. 提示用户
        this.$message.success('编辑角色成功')
        // 4. 退出编辑状态
        // 以下提示错误 eslint的误判
        // eslint-disable-next-line require-atomic-updates
        // row.isEdit = false
        // row.name = row.editRow.name
        // row.description = row.editRow.description
        // row.state = row.editRow.state
        // Object.assign() 浅拷贝 - 克隆 / 合并
        // Object.assign() 将一个或者多个源对象中属性复制到目标对象
        // Object.assign(目标对象, 源对象1, 源对象2, ...)
        // 5. 取消编辑状态  更新页面数据   row.name / row.description / row.state
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
      }
    },
    // 删除角色
    async del(row) {
      await delRole(row.id)
      this.$message.success('删除角色成功')
      if (this.list.length === 1 && this.pageParams.page > 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },
    // 切换分页
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值当前页码
      this.getRoleList()
    },
    // 确认新增角色
    async confirm() {
      await this.$refs.roleForm.validate()
      await addRole(this.roleForm)
      this.$message.success('新增角色成功')
      this.getRoleList()
      this.cancel()
    },
    // 关闭弹层
    cancel() {
      this.$refs.roleForm.resetFields() // 重置表单数据
      this.showDialog = false // 关闭弹层
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
